package action;

import Impl.MessageDaoImpl;
import entity.Message;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

@WebServlet(name = "MessagesAction")
public class MessageAction extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        System.out.println("--------正在执行MessageAction-----------");
        request.setCharacterEncoding("utf-8");
        MessageDaoImpl messageDao = new MessageDaoImpl();
        String method =request.getParameter("method");
        List<Message> messages = new ArrayList<>();
        if (method.equals("receive")){
            String receiver = (String) request.getSession().getAttribute("uname");
             messages = messageDao.findMessageByrecipient(receiver);
            request.getSession().setAttribute("messages",messages);
            request.getRequestDispatcher("/message.jsp").forward(request,response);
        }else{
            String sender = (String) request.getSession() .getAttribute("uname");
            messages=messageDao.findMessageBysender(sender);
            request.getSession().setAttribute("messages",messages);
            request.getRequestDispatcher("/send_message.jsp").forward(request,response);
        }

    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doPost(request,response);
    }
}
